package com.zzyl.nursing.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.dto.UserLoginRequestDto;
import com.zzyl.nursing.domain.pojo.FamilyMember;
import com.zzyl.nursing.domain.vo.LoginVo;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 老人家属Service业务层处理
 * @author alexis
 * @date 2025-05-26
 */
@Service
@Slf4j
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private TokenService tokenService;
    
    // 给定的昵称前缀数组
    private static final String[] NICKNAME_PREFIXES={"阳光","快乐","活力","暖心","智慧","勇敢","善良","可爱","优雅","魅力"};
    
    private static final Random RANDOM=new Random();
    
    /**
     * 查询老人家属
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return familyMemberMapper.selectById(id);
    }
    
    /**
     * 查询老人家属列表
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }
    
    /**
     * 新增老人家属
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return familyMemberMapper.insert(familyMember);
    }
    
    /**
     * 修改老人家属
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return familyMemberMapper.updateById(familyMember);
    }
    
    /**
     * 批量删除老人家属
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }
    
    /**
     * 删除老人家属信息
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return familyMemberMapper.deleteById(id);
    }
    
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 一、认证：openId-->family_member表查询
        String code=userLoginRequestDto.getCode();
        String openId=wechatService.getOpenId(code);
        FamilyMember member=this.getOne(Wrappers.<FamilyMember>lambdaQuery()
                                                .eq(FamilyMember::getOpenId,openId));
        // 二、表维护：获取用户phone和昵称数据-->新增用户或者修改用户
        String accessToken=wechatService.getAccessToken();
        String phoneNumber=wechatService.getPhoneNumber(accessToken,userLoginRequestDto.getPhoneCode(),openId);
        String nickname=generateNickname(phoneNumber);
        // 新用户：新增
        if (ObjectUtil.isNull(member)) {
            member=FamilyMember.builder()
                               .phone(phoneNumber)
                               .name(nickname)
                               .openId(openId)
                               .build();
            this.save(member);
        } else {
            // 老用户：修改手机号(表中手机号和现在登录手机号不一致才会修改)
            if (!StrUtil.equals(member.getPhone(),phoneNumber)) {
                member.setPhone(phoneNumber);
                this.updateById(member);
            }
        }
        // 三、产生token构建LoginVo对象
        Map<String, Object> claims=MapUtil.<String, Object>builder()
                                          .put("userId",member.getId())
                                          .build();
        String token=tokenService.createToken(claims);
        return LoginVo.builder()
                      .token(token)
                      .nickName(nickname)
                      .build();
    }
    
    @Override
    public void getMy() {
        log.info("FamilyMemberService中线程==>{}",Thread.currentThread()
                                                        .getId());
        Long userId=UserThreadLocal.getValue();
        log.info("从ThreadLocal中获取用户id为：{}",userId);
    }
    
    /**
     * 生成随机昵称，由随机前缀和手机号后4位组成
     * @param phoneNumber 手机号
     * @return 随机昵称
     */
    private String generateNickname(String phoneNumber) {
        // 随机选取一个前缀
        String prefix=NICKNAME_PREFIXES[RANDOM.nextInt(NICKNAME_PREFIXES.length)];
        // 获取手机号后4位
        String suffix=phoneNumber.substring(Math.max(0,phoneNumber.length() - 4));
        return prefix + suffix;
    }
}
